package com.hd.trans.framework.dialog

import android.annotation.SuppressLint
import android.view.KeyEvent
import android.view.MotionEvent
import android.view.View
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import com.hd.trans.framework.click.XClickUtil

/**
 * 作者：qianjujun
 * 邮箱：qianjujun@163.com
 * 时间: 2017-05-26  17:38
 */
@SuppressLint("ClickableViewAccessibility")
open class CstBindPop<T : ViewDataBinding>(parentView:View?,view: View, outSideDismiss:Boolean = true,isTouch:Boolean = true) : CstPup(parentView,view,isTouch,true), View.OnClickListener {

    constructor(view: View,outSideDismiss:Boolean = true,isTouch:Boolean = true):this(null,view,outSideDismiss,isTouch)

    constructor(parentView:View?,view: View, outSideDismiss:Boolean = true):this(parentView,view,outSideDismiss,true)

    private var mWidth = 0
    private var mHeight = 0
    protected var mDataBinding: T = DataBindingUtil.bind(view)!!

    open val dimAmount: Float = 0.6f

    final override fun getMDimAmount(): Float {
        return dimAmount
    }

    protected fun init(mDataBinding: T) {}

    override fun onClick(v: View) {
        if (!XClickUtil.isValidClick()) {
            return
        }
        onViewClick(v)
    }

    open fun onViewClick(v: View) {}

    open fun onBackPressed() = true

    init {
        init(mDataBinding)

        if(!outSideDismiss && isTouch){
            setTouchInterceptor { _, event ->
                val x = event.x.toInt()
                val y = event.y.toInt()

                if(mWidth==0){
                    mWidth = contentView.measuredWidth
                }
                if(mHeight==0){
                    mHeight = contentView.measuredHeight
                }

                var result =  event.action== MotionEvent.ACTION_OUTSIDE

                var outSide = false
                if(event.action== MotionEvent.ACTION_DOWN){
                    outSide = ((x < 0) || (x >= mWidth) || (y < 0) || (y >= mHeight))
                }

                result = result or outSide

                result

            }
        }

        mDataBinding.root.setOnKeyListener { _, keyCode, event ->
            if (keyCode == KeyEvent.KEYCODE_BACK && event.action == MotionEvent.ACTION_UP) {
                !onBackPressed()
            } else false
        }

    }
}